/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ArkMethod, Stmt, ArkClass } from 'arkanalyzer/lib';
import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { BaseChecker, BaseMetaData } from '../BaseChecker';
import { Rule, Defects, MatcherTypes, MatcherCallback, CheckerUtils } from '../../Index';
import { IssueReport } from '../../model/Defects';
import { ClassMatcher } from '../../matcher/Matchers';

const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'NestedPostFrameCallbackCheck');

const gMetaData: BaseMetaData = {
    severity: 3,
    ruleDocPath: 'docs/nested-post-frame-callback-check.md',
    description: 'Avoid nested postFrameCallback calls.'
};

// 字符串常量定义
const POST_FRAME_CALLBACK_METHOD = 'postFrameCallback';
const UICONTEXT_CLASS_NAME = 'UIContext';

export class NestedPostFrameCallbackCheck implements BaseChecker {
    readonly metaData: BaseMetaData = gMetaData;
    public rule: Rule;
    public issues: IssueReport[] = [];

    private clsMatcher: ClassMatcher = {
        matcherType: MatcherTypes.CLASS
    };

    public registerMatchers(): MatcherCallback[] {
        return [{ matcher: this.clsMatcher, callback: this.check }];
    }

    public check = (arkClass: ArkClass): void => {
        // 检查父类名是否为 FrameCallback
        const superClass = arkClass.getSuperClass && arkClass.getSuperClass();
        if (!superClass || superClass.getSignature().getClassName() !== 'FrameCallback') {
            return;
        }
        // 遍历所有方法体，查找 postFrameCallback 调用
        for (const method of arkClass.getMethods()) {
            if (method.getName() !== 'onFrame') {
                continue;
            }
            const stmts = method.getBody()?.getCfg()?.getStmts() ?? [];
            for (const stmt of stmts) {
                const invoke = CheckerUtils.getInvokeExprFromStmt(stmt);
                if (!invoke) {
                    continue;
                }
                const methodName = invoke.getMethodSignature().getMethodSubSignature().getMethodName();
                if (methodName === 'postFrameCallback') {
                    this.reportIssue(stmt, method);
                }
            }
        }
    };

    private reportIssue(stmt: Stmt, arkMethod: ArkMethod): void {
        const filePath = arkMethod.getDeclaringArkFile().getFilePath();
        const severity = this.rule.alert ?? this.metaData.severity;
        // 获取调用表达式
        const invoke = CheckerUtils.getInvokeExprFromStmt(stmt);
        if (!invoke) {
            return;
        }
        // 获取语句起始行号
        const reportPosition = stmt.getOriginPositionInfo();
        if (!reportPosition) {
            return;
        }
        const line = reportPosition.getLineNo();
        // 获取源码原始行文本
        const arkFile = arkMethod.getDeclaringArkFile();
        const code = arkFile.getCode();
        const lines = code.split(/\r?\n/);
        const lineText = lines[line - 1] || '';
        const methodIdx = lineText.indexOf(POST_FRAME_CALLBACK_METHOD);
        if (methodIdx === -1) {
            return;
        }
        const startCol = methodIdx + 1; // 列号通常1-based
        const endCol = startCol + POST_FRAME_CALLBACK_METHOD.length - 1;

        const defect = new Defects(
            line,
            startCol,
            endCol,
            this.metaData.description,
            severity,
            this.rule.ruleId,
            filePath,
            this.metaData.ruleDocPath,
            true,
            false,
            false
        );
        this.issues.push(new IssueReport(defect, undefined));
    }
}
